package src.comman.duke.display 
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.utils.ByteArray;
	
	/**
	 * 蒙版图片处理
	 * @original http://blog.sina.com.cn/s/blog_55ff5d2d0100qoce.html
	 */
	public class ColorAndAlphaImage extends Bitmap 
	{
		private var _greyScaled:BitmapData;
		private var _coloredImage:BitmapData;
		private var _newBitmapData:BitmapData;
		
		private var _origVector:Vector.<uint>;
		private var _colorVector:Vector.<uint>;
		private var _vector:Vector.<uint>;
		public function ColorAndAlphaImage(bitmapData:BitmapData=null, greyScaled:BitmapData) 
		{
			_vector = new Vector.<uint>();
			_greyScaled = greyScaled;
			_coloredImage = bitmapData;
			_newBitmapData = new BitmapData(bitmapData.width, bitmapData.height, true, 0x00000000);
			_newBitmapData.lock();
			
			super(_newBitmapData);
			_origVector = _greyScaled.getVector(_greyScaled.rect);
			_origVector.fixed = true;
			
			_colorVector = _coloredImage.getVector(_coloredImage.rect);
			_colorVector.fixed = true;
			
			readAndWrite();
		}
		
		private function readAndWrite():void{
			var totalPixels:uint = _colorVector.length;
			var i:int = 0;
			_vector.length = totalPixels;
			_vector.fixed = true;
			
			while (--totalPixels){
				_vector[totalPixels]=int(shiftPixels(int (_origVector[totalPixels]),int(_colorVector[totalPixels])));
			}
		}
		
		private function shiftPixels(alphaChannel:uint, colorChannel:uint):uint{
			var decimal:uint=alphaChannel>>16&0xFF;
			var argb : uint = (decimal << 24) | (ColorAndAlphaCompared.extractRED(colorChannel)<<16) | (ColorAndAlphaCompared.extractGREEN(colorChannel)<<8) | ColorAndAlphaCompared.extractBLUE(colorChannel);
			return argb;
		}   
       
		private function dispose():void{
			_greyScale.dispose();
			_coloredImage.dispose();
			_vector=_colorVector=_origVector=null;
			_greyScale=_coloredImage=null;
		}
      
		static private function extractALPHA(hex:uint):uint{
			return hex>>24 & 0xff;
		}
      
		static private function extractRED(hex : uint):uint{
			return hex>>16 & 0xff;
		}
      
		static private function extractGREEN(hex : uint):uint{
			return hex>>8 & 0xff;
		}
     
		static private function extractBLUE(hex : uint):uint{
			return hex & 0xff;
		}
	}
}